package com.ruoyi.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 元对象字段自动填充处理
 */
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_BY = "createBy";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_BY = "updateBy";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        Object createBy = metaObject.getValue(CREATE_BY);
        if (createBy == null || StringUtils.isBlank(createBy.toString())) {
            metaObject.setValue(CREATE_BY, getUserName());
        }
        if (metaObject.getValue(CREATE_TIME) == null) {
            metaObject.setValue(CREATE_TIME, LocalDateTime.now().toString());
        }
        setUpdate(metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setUpdate(metaObject);
    }

    private void setUpdate(MetaObject metaObject) {
        Object updateBy = metaObject.getValue(UPDATE_BY);
        if (updateBy == null || StringUtils.isBlank(updateBy.toString())) {
            metaObject.setValue(UPDATE_BY, getUserName());
        }
        if (metaObject.getValue(UPDATE_TIME) == null) {
            metaObject.setValue(UPDATE_TIME, LocalDateTime.now().toString());
        }
    }

    private String getUserName() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return loginUser == null ? null : loginUser.getUsername();
    }
}
